<template>
  <view class="wrap">
    <uv-navbar :fixed="false" title="发文件" safeAreaInsetTop placeholder :border='false'>
      <template v-slot:left>
        <view class="navEditName nav-left" @click="goBack">取消</view>
      </template>
      <template v-slot:right>
        <view class="navEditName nav-right" @click="tap">保存</view>
      </template>
    </uv-navbar>
    <view class="bigTitle">
      <view style="width: 100%;height: 20rpx;"></view>
      <uv-input placeholder="请输入标题" border="none" v-model="base.title" placeholderStyle='font-weight: 500; font-size: 36rpx; color: #B8B8B8;' fontSize='36rpx' color="#333" :customStyle="{height: '90rpx'}"></uv-input>
      <view style="width: 100%;height: 30rpx;"></view>
      <uv-line color="#E6E6E6"></uv-line>
    </view>
    <view class="content">
      <uv-textarea v-model="base.content" :confirmType='null' placeholder="请输入不超过300字的简介，欢迎发表优质的原创文章" border='none' maxlength='300' height="100%" placeholderStyle='font-weight: 400; font-size: 32rpx; color: #B8B8B8;' textStyle='font-weight: 400; font-size: 32rpx; color: #000000;' customStyle='height: 100%'></uv-textarea>
    </view>
    <!-- <uv-overlay :show="scoll" zIndex='998' opacity='0' @click="scoll = !scoll"></uv-overlay> -->
    <view class="footer">
      <!-- <view class="imgs" v-if="base.images.length">
        <view class="item" v-for="(item, index) in base.images" :key="index">
          <image :src="setUrl(item)" class="img" mode="aspectFill" @click="previewImage(item)"></image>
          <image src="../../static/delete.png" class="delete" @click="imgClick(index)"></image>
        </view>
      </view> -->
      <view class="filed" v-if="base.files.length">
        <view class="files">
          <view class="call" v-for="(item, index) in base.files">
            <view class="flieIcon">{{ setUrl(item).substring(setUrl(item).lastIndexOf(".") + 1) }}</view>
            <view class="name">{{ setUrl(item) }}</view>
            <view class="delete" @click="fileClick(index)"><image src="../../static/delete.png" class="img"></image></view>
          </view>
        </view>
      </view>
      <view class="tips" v-if="talkSelect.length">
        <view class="test" v-for="(item,index) in talkSelect" :key="index">#{{ item.name }}</view>
      </view>
      <view class="fasc">
        <!-- <view class="cell" @click="chooseImage">
          <image src="../../static/uploadImage.png" class="img"></image>
        </view> -->
        <view class="cell" @click="chooseFile">
          <image src="../../static/filed.png" class="img"></image>
        </view>
        <!-- <view class="cell" @click="scoll = !scoll">
          <image src="../../static/hashtag.png" class="img" v-if="!scoll"></image>
          <image src="../../static/hashtag-1.png" class="img" v-else></image>
        </view> -->
      </view>
      <view class="base scoll">
        <uv-safe-bottom></uv-safe-bottom>
        <view class="topic">
          <view class="title">
            <view class="left">
              兴趣标签 <text class="desc">(必填，做多选择三个标签)</text>
            </view>
          </view>
          <view class="list">
            <view class="item" :class="{active: base.tag_ids.findIndex(o => o.id == item.id) >= 0}" v-for="(item, index) in talkList" :key="index" @click="addTag(item)">{{ item.name }}</view>
          </view>
        </view>
        <view class="topic">
          <view class="title" @click="goReveal">
            <view class="left">
              利益披露 <text class="desc">(必填)</text>
            </view>
            <uv-icon name='arrow-right' size="30rpx" color="#B8B8B8"></uv-icon>
          </view>
          <view class="source">{{ desc[base.copyright] }}</view>  
        </view>
        <!-- <view class="addTopic" @click="goSearch">
          <uv-icon name="plus" size="24rpx" color="#2B2B2B" bold></uv-icon>
          <text class="font">添加话题</text>
        </view> -->
      </view>
      <uv-safe-bottom></uv-safe-bottom>
    </view>
    <view class="safe"></view>
    <uv-safe-bottom></uv-safe-bottom>
    
    <uv-modal ref="modal" title="需要文件访问权限" showCancelButton confirmColor='#E43222' confirmText='去授权' @confirm="confirm">
      <view>
        您还未授权本应用读取文件。为保证您可以正常上传文件，请在权限设置页面打开文件访问权限（不同手机厂商表述可能略有差异）请根据自己手机品牌设置
      </view>
    </uv-modal>
    <uv-modal ref="storageModal" title="提示" showCancelButton confirmColor='#E43222' confirmText='保存' @cancel='cancel' @confirm="keyStorage">
      <view>
        是否保存草稿箱？
      </view>
    </uv-modal>
  </view>
</template>

<script setup>
import { ref, computed } from 'vue';
import { useOrder } from '@/store';
import { onShow, onUnload, onLoad } from "@dcloudio/uni-app";
import { post } from '@/api';
import { toast, setUpload, setUrl } from '@/common';
// #ifdef APP-PLUS
const lemonjkFileSelect = uni.requireNativePlugin('lemonjk-FileSelect');
// #endif

const modal = ref(null);
const storageModal = ref(null);
const desc = ref({
  1: '转载，不作为证券推荐或投资建议，意在分享信息，作者不保证内容准确性。',
  2: '原创，不作为证券推荐或投资建议，制止发文时，作者不持有相关标的。',
  3: '原创，不作为证券推荐或投资建议，制止发文时，作者持有相关标的，下一个交易日内可能随机卖出。',
  4: '原创，不作为证券推荐或投资建议，制止发文时，作者持有相关标的，下一个交易日内没有卖出计划。'
})

let content = ref('');
let base = ref({
  title: '',
  content: '',
  files: ['/fefefe/dsdsdds.png', '/fefefe/dsdsdds.png'],
  tag_ids: [],
  copyright: 1
})
let talkSelect = ref([]);
let talkList = ref([]);

let body = computed(() => {
  const store = useOrder();
  return uni.$uv.deepClone(store.group);
});

onLoad((option) => {
  const issue = uni.getStorageSync('issueFile');
  if(issue){
    const val = uni.$uv.deepClone(issue);
    base.value.title = val.title ? val.title : '';
    base.value.content = val.content ? val.content : '';
    base.value.files = (val.files && val.files.length) ? val.files : [];
    base.value.tag_ids = (val.tag_ids && val.tag_ids.length) ? val.tag_ids : [];
    base.value.copyright = val.copyright;
  }
  getTalkList();
})
onShow(() => {
  if(useOrder().reveal){
    base.value.copyright = useOrder().reveal;
    useOrder().setReveal('');
  }
})
onUnload(() => {
  console.log('页面卸载');
})

// tab禁止点击多次
let debounce = false;
function tap(){
  if(debounce) return;
  const params = {
    type: 2
  };
  if(base.value.tag_ids.length){
    params.tag_ids = base.value.tag_ids.map(e => e.id).toString();
  }else{
    params.tag_ids = '';
  }
  if(base.value.files.length){
    params.files = base.value.files.toString();
  }else{
    params.files = '';
  }
  if(!base.value.title) return toast('请输入标题');
  if(!base.value.content) return toast('请输入内容');
  if(!base.value.copyright) return toast('请选择版本信息');
  params.title = base.value.title;
  params.content = base.value.content;
  params.copyright = base.value.copyright;
  debounce = true;
  
  post('api/news/createNews', params).then(res => {
    debounce = false;
    if(res.code == 1){
      toast('发布成功');
      uni.removeStorageSync('issueFile');
      setTimeout(() => {
        uni.navigateBack({
          delta: 1
        });
      }, 1000)
    }
  })
}
// 获取兴趣列表
function getTalkList(){
  const params = {
    type: 2,
    page: 1,
    limit: 200
  }
  post('api/user/getTagList', params).then(res => {
    if(res.code == 1){
      const data = res.data;
      talkList.value = data;
    }
  })
}
// 选择文件并上传
function chooseFile(){
  // #ifndef APP-PLUS
  return toast('请打开APP上传');
  // #endif
  // #ifdef APP-PLUS
  if(base.value.files.length >= 5) return toast('最多只能上传5份文件');
  lemonjkFileSelect.showPicker({
    mimeType: '*/*',
    utisType: 'public.data'
  }, res => {
    let os = uni.$uv.os();
    if(os == 'android'){
      if(res.code == 1001){
        modal.value.open();
      }else if(res.code == 0){
        setUpload([res.files[0].filePath]).then(file => {
          console.log(file);
          base.value.files = [...base.value.files, file];
        })
      }else{
        toast(res.detail)
      }
    }else{
      if(res.code == 0){
        setUpload([res.files[0].filePath]).then(file => {
          base.value.files = [...base.value.files, file];
        })
      }else{
        toast(res.detail)
      }
    }
  })
  // #endif
}
function confirm(){
  // 跳转到应用设置页
  lemonjkFileSelect.gotoSetting();  
}
// 删除文件选择
function fileClick(index){
  base.value.files.splice(index, 1);
}
// 选择话题标签
function addTag(row){
  const index = base.value.tag_ids.findIndex(o => o.id == row.id);
  if(index >= 0){
    base.value.tag_ids.splice(index, 1);
    return
  }else{
    if(base.value.tag_ids.length >= 3){
      return;
    }
    base.value.tag_ids.push(row);
  }
}
function goSearch(){
  uni.navigateTo({
    url: '/pages/group/searchTalk'
  });
}
function keyStorage(){
  uni.setStorageSync('issueFile', base.value);
  uni.navigateBack({
    delta: 1
  });
}
function cancel(){
  storageModal.value.close();
  uni.removeStorageSync('issueFile');
  uni.navigateBack({
    delta: 1
  });
}
function goBack(){
  const value = base.value;
  if(value.title || value.content || value.files.length || value.tag_ids.length){
    storageModal.value.open();
  }else{
    cancel()
  }
}
function goReveal(){
  uni.navigateTo({
    url: `/pages/dynamic/reveal?index=${base.value.copyright}`
  });
}
</script>

<style lang="scss" scoped>
  .safe{
    width: 100%;
    height: 208rpx;
    background-color: #fff;
  }
  .footer{
    width: 100%;
    position: fixed;
    left: 0;
    bottom: 0;
    z-index: 999;
    border-top: 1px solid #F5F5F5;
    background-color: #fff;
    .tips{
      padding: 0 30rpx;
      padding-top: 20rpx;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      .test{
        font-weight: 400;
        font-size: 32rpx;
        color: #465B89;
        margin-right: 20rpx;
      }
    }
    .filed{
      width: 100%;
      padding: 30rpx;
      .files{
        padding: 16rpx;
        background-color: #F5F5F5;
        .call{
          background-color: #FFFFFF;
          border-radius: 12rpx;
          // padding: 20rpx;
          padding-right: 20rpx;
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
          margin-right: 12rpx;
          margin-bottom: 16rpx;
          &:last-child{
            margin-bottom: 0;
          }
          .flieIcon{
            width: 100rpx;
            height: 100rpx;
            padding: 10rpx;
            font-size: 30rpx;
            color: #FFFFFF;
            background-color: #E55D52;
            border-radius: 10rpx;
            margin-right: 10rpx;
            padding-bottom: 16rpx;
            display: flex;
            align-items: center;
            justify-content: center;
          }
          .delete{
            width: 24rpx;
            height: 24rpx;
            font-size: 0;
          }
          .name{
            font-weight: 400;
            font-size: 28rpx;
            color: #2B2B2B;
            width: 0;
            flex: 1;
            padding-right: 30rpx;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
          }
        }
      }
    }
    .imgs{
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      width: 100%;
      padding: 0 30rpx;
      padding-top: 20rpx;
      .item{
        width: 150rpx;
        height: 150rpx;
        margin-right: 20rpx;
        border-radius: 12rpx;
        margin-bottom: 20rpx;
        position: relative;
        .delete{
          width: 24rpx;
          height: 24rpx;
          position: absolute;
          right: -12rpx;
          top: -12rpx;
        }
      }
    }
    .addTopic{
      display: flex;
      align-items: center;
      justify-content: center;
      width: 100%;
      padding-top: 36rpx;
      padding-bottom: 30rpx;
      border-top: 1px solid #E6E6E6;
      .font{
        font-weight: 400;
        font-size: 32rpx;
        color: #2B2B2B;
        padding-left: 12rpx;
      }
    }
    .base{
      transition: all .5s;
      max-height: 0;
      &.scoll{
        max-height: 1500rpx;
      }
    }
    .topic{
      padding: 0 30rpx;
      padding-bottom: 30rpx;
      .list{
        width: 100%;
        white-space: nowrap;
        display: flex;
        align-items: center;
        flex-wrap: wrap;
        .item{
          font-weight: 400;
          font-size: 28rpx;
          color: #2B2B2B;
          padding: 0 24rpx;
          background-color: #F5F5F5;
          height: 64rpx;
          line-height: 64rpx;
          border-radius: 64rpx;
          margin-right: 24rpx;
          margin-bottom: 20rpx;
          text-align: center;
          &.active{
            background-color: #E43222;
            color: #fff;
          }
        }
      }
      .source{
        font-weight: 400;
        font-size: 28rpx;
        color: #737373;
      }
      .title{
        display: flex;
        align-items: center;
        justify-content: space-between;
        width: 100%;
        .left{
          font-weight: 500;
          font-size: 32rpx;
          color: #2B2B2B;
          padding-bottom: 24rpx;
          .desc{
            font-weight: 400;
            font-size: 24rpx;
            color: #999999;
            padding-left: 10rpx;
          }
        }
      }
    }
    .fasc{
      width: 100%;
      padding: 40rpx 30rpx;
      display: flex;
      align-items: center;
      .cell{
        margin-right: 50rpx;
        width: 40rpx;
        height: 40rpx;
      }
    }
  }
  .bigTitle{
    padding: 0 24rpx;
    :deep(.uv-input__content__prefix-icon){
      display: none;
    }
  }
  .content{
    width: 100%;
    background-color: #fff;
    height: 45vh;
  }
  .navEditName{
    font-weight: 400;
    font-size: 28rpx;
    &.nav-left{
      color: #737373;
    }
    &.nav-right{
      color: #E43222;
    }
  }
</style>